<!-- 角色授权菜单抽屉 -->
<!-- created by lx 2023/3/22 -->
<template>
  <div>
    <!-- 按钮 -->
    <a-link :disabled="disabled" @click="openDrawer">授权</a-link>

    <!-- 抽屉：授权 -->
    <a-drawer
      :visible="visible"
      title="授权"
      :width="360"
      @before-ok="authorizeRole"
      @cancel="closeDrawer"
    >
      <a-spin :loading="loadingAuth || loadingRole">
        <a-checkbox-group
          v-model:model-value="checkedKeys"
          direction="vertical"
        >
          <a-checkbox v-for="item in roleList" :key="item.id" :value="item.id">
            {{ item.name }}
          </a-checkbox>
        </a-checkbox-group>
      </a-spin>
    </a-drawer>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { queryRoleRecordList } from '@/api/system/role';
  import { queryUserRoleList, updateUserRole } from '@/api/system/permission';
  import { RoleRecord } from '@/api/system/model/roleModel';

  const props = defineProps({
    userId: {
      type: [String, Number],
      required: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  });

  const visible = ref<boolean>(false);
  const openDrawer = () => {
    getRoleList();
    getAuthList();
    visible.value = true;
  };
  const closeDrawer = () => {
    visible.value = false;
  };

  const loadingRole = ref<boolean>(false);
  const loadingAuth = ref<boolean>(false);

  const checkedKeys = ref<(string | number | boolean)[]>([]);

  const roleList = ref<RoleRecord[]>([]);
  const getRoleList = async () => {
    loadingRole.value = true;
    try {
      const { data } = await queryRoleRecordList();
      roleList.value = data;
    } finally {
      loadingRole.value = false;
    }
  };
  const getAuthList = async () => {
    loadingAuth.value = true;
    checkedKeys.value = [];
    try {
      const { data } = await queryUserRoleList(props.userId as string);
      checkedKeys.value = [...data];
    } finally {
      loadingAuth.value = false;
    }
  };

  // func：保存授权信息
  const authorizeRole = async (done: (closed: boolean) => void) => {
    try {
      await updateUserRole({
        userId: props.userId as string,
        roleIds: checkedKeys.value as string[],
      });
      Message.success('修改成功');
    } finally {
      done(true);
      closeDrawer();
    }
  };
</script>
